package com.betty.contentresolver;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    ListView list_call;
    //   内容解析者--用来从内容提供者中获取数据
    ContentResolver resolver;
    SimpleCursorAdapter adapter;
    String[] from = new String[]{CallLog.Calls.DATE, CallLog.Calls.NUMBER};
    int[] to = new int[]{R.id.tv_data, R.id.tv_number};
    private String uri = "content://call_log/calls";
    //    要查询的列
    private String[] columns = new String[]{CallLog.Calls._ID, CallLog.Calls.NUMBER,
            CallLog.Calls.DATE, CallLog.Calls.TYPE};
    Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list_call = (ListView) findViewById(R.id.lv);
        resolver = getContentResolver();
        adapter = new SimpleCursorAdapter(this, R.layout.list_item, null, from, to);

    }

    //    Uri统一资源标识符；Url统一资源标定符
    public void query(View view) {
        Cursor cursor = resolver.query(Uri.parse(uri), columns, null, null, null);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor,
                new String[]{CallLog.Calls.DATE, CallLog.Calls.NUMBER}, new int[]{R.id.tv_data, R.id.tv_number});
        adapter.swapCursor(cursor);
        list_call.setAdapter(adapter);
//    点击查询联系人
//    public void query(View view){
//        new MyAsyncTask().execute();
//    }
//
    }

    @Override
    protected void onDestroy() {
        if (cursor != null)
            cursor.close();
        super.onDestroy();
//
//    class MyAsyncTask extends AsyncTask<String,Void,Cursor>{
//       @Override
//       protected void onPreExecute() {
//           super.onPreExecute();
//       }
//
//       @Override
//       protected Cursor doInBackground(String... params) {
//           cursor=resolver.query(CallLog.Calls.CONTENT_URI,columns,null,null,null);
//           adapter.swapCursor(cursor);
//           return cursor;
//       }
//
//       @Override
//       protected void onPostExecute(Cursor s) {
//           super.onPostExecute(s);
//       }
//   }

    }
}